package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Errors;
import bean.GebruikerBean;
import bean.VeilingBean;
import exceptions.GebruikerBestaatNietException;
import exceptions.VeilingBestaatNietException;

/**
 * Servlet implementation class BiedingServlet
 */
public class BiedingServlet extends BasisServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BiedingServlet()
	{
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected synchronized void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		melding(Errors.E009.getErorr(), request, response);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected synchronized void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		login(request);
		HttpSession session = request.getSession();

		if (!request.getParameter("amount").toString().equals("") && !request.getParameter("id").toString().equals(""))
		{
			try
			{
				int id = Integer.parseInt(request.getParameter("id").toString());
				int amount = Integer.parseInt(request.getParameter("amount").toString());
				GebruikerBean gebruiker = gDao.getGebruiker(session.getAttribute("mail").toString());
				VeilingBean veiling = null;
				try
				{
					veiling = vDao.getVeiling(id, bDao);
				} catch (VeilingBestaatNietException e)
				{
					e.printStackTrace();
				}

				if (offer(gebruiker, veiling, amount))
				{
					RequestDispatcher view = request.getRequestDispatcher("index.html?action=kijkveiling&veiling="
							+ veiling.getId());
					view.forward(request, response);
					return;
				} else
				{
					melding(Errors.E004.getErorr(), request, response);
				}
			} catch (GebruikerBestaatNietException e)
			{
				melding(Errors.E001.getErorr(), request, response);
			} catch (NumberFormatException e)
			{
				melding(Errors.E005.getErorr(), request, response);
			}
		} else
		{
			melding(Errors.E001.getErorr(), request, response);
		}
	}

	private synchronized boolean offer(GebruikerBean gebruiker, VeilingBean veiling, int amount)
	{
		if (gebruiker != null && veiling != null && amount > 0)
		{
			if (veiling.getMinimumBod() < amount && veiling.getMaxBod().getBod() < amount)
			{
				bDao.addBieding(gebruiker, veiling, amount);
				return true;
			}
		}
		return false;
	}
}
